package com.xxyf.emil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @Author 小小怡飞
 * @Date 2022/8/4 16:46
 * @Version JDK 8
 */
@Service
public class Emali {
    @Value("${spring.mail.username}")
    String form;
    @Autowired
    private JavaMailSender mailSender;

    @Async
    public void send(String title, String text, String to, File... path){
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage,true);
        } catch (MessagingException e) {
            System.out.println("错误");
            e.printStackTrace();
        }
        try {
            helper.setSubject(title);
            helper.setText(text);
            helper.setTo(to);
            helper.setFrom(form);
            if(path!=null){
            for (File s1 : path) {
                String s = s1.getPath();
                int i = s.lastIndexOf("\\");
                String substring;
                if (i==-1){
                    System.out.println("分割没找到");
                    substring=s;
                }else {
                substring= s.substring(i + 1);
                }
                System.out.println(substring);
                helper.addAttachment(substring,s1);
            }}
        }catch (MessagingException e){
            System.out.println("发送失败");
            e.printStackTrace();
        }


        mailSender.send(mimeMessage);
    }
    @Async
    public void send(String title,String text,String to){
        send(title,text,to,null);
    }

}
